<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import jzsmService from '@/api/jzsm'
/*
 * 打开弹窗
 */
//
const emit = defineEmits(['refresh'])
const dialogVisible = ref(false)
const currentRow = ref()
const openDialog = () => {
  dialogVisible.value = true
}

/*
 * 确定按钮
 */
// 保存借阅审核结果入参
const form = ref({
  bmsahList: [{ val: '' }] as { val: string }[],
})

const rules = reactive<FormRules<any>>({
  thyy: [{ required: true, message: '必填', trigger: 'change' }],
})

const addRow = () => {
  form.value.bmsahList.push({ val: '' })
}

const deleteRow = (row: { val: string }) => {
  const i = form.value.bmsahList.findIndex((bmsah) => bmsah === row)
  form.value.bmsahList.splice(i, 1)
}

const confirm = () => {
  const params = { bmsahList: form.value.bmsahList.map((el) => el.val) }
  jzsmService
    .sdjsJzsm(params)
    .then(() => {
      dialogVisible.value = false
      ElMessage({ type: 'success', message: '接收成功' })
      emit('refresh')
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
const closeDialog = () => {
  currentRow.value = undefined
}
defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="手动接收"
    width="600"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <div class="dialog-form">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item
          v-for="(bmsah, i) in form.bmsahList"
          :key="i"
          :label="i === 0 ? '部门受案号' : ''"
        >
          <el-input class="bmsah-input" v-model="bmsah.val" />
          <el-button v-if="i === 0" type="primary" @click="addRow">+</el-button>
          <el-button v-else type="danger" @click="deleteRow(bmsah)">-</el-button>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="!currentRow" type="primary" style="margin-left: 10px" @click="confirm"
          >确定</el-button
        >
        <el-button type="default" style="margin-left: 10px" @click="dialogVisible = false"
          >取消</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 10px;
}
.bmsah-input {
  width: 80%;
  margin-right: 10px;
  & + .el-button {
    min-width: auto;
  }
}
</style>
